﻿using System;
using System.Collections.Generic;
using MediaBrowser.Library.Plugins;
using MediaBrowser.Library.Logging;
using MediaBrowser.Library;
using MediaBrowser.Library.Entities;
using MusicPlugin.Library.EntityDiscovery;
using MediaBrowser.Library.Factories;
using MusicPlugin.Library.Playables;
using MusicPlugin.Library.Entities;
using MusicPlugin.Code.ModelItems;
using System.Reflection;
using MusicPlugin.Library.Helpers;
using MusicPlugin.Util;
using Microsoft.MediaCenter;
using System.IO;
using MusicPlugin.Views;
using MediaBrowser;
using System.Diagnostics;
using MusicPlugin.Code;

namespace MusicPlugin
{
    public class Plugin : BasePlugin
    {  
        Kernel _kernel;

        public override void Init(Kernel kernel)
        {
            _kernel = kernel;
                        
            Logger.ReportInfo(string.Format("Tyring to load {0} v{1} loaded by {2}.", Name, LatestVersion.ToString(), AppDomain.CurrentDomain.FriendlyName));
            bool isConfigurator = !AppDomain.CurrentDomain.FriendlyName.Contains("ehExtHost");
            
            if (Settings.ValidateSettings(kernel.ConfigData.InitialFolder, true))
            {
                LoadLibraries(kernel, isConfigurator);
            }

            //add our music specific menu items
            SetupKernel(kernel, isConfigurator);

            if (!Settings.Instance.LoadNormalLibrary && !Settings.Instance.LoadiTunesLibrary)
                Logger.ReportInfo("Music plugin, iTunes nor Normal Music enabled, probably using folder specification (vf files) via configurator, PLEASE DO NOT USE VFs USE PLUGIN CONFIGURATOR.");

            //SetupTestingTimer();
                        
        }

        private void SetupKernel(Kernel kernel, bool isConfigurator)
        {
            if (!isConfigurator)
            {
                kernel.AddMenuItem(new MenuItem("Queue All", "resx://MediaBrowser/MediaBrowser.Resources/Lines", this.queue, new List<Type>() { typeof(ArtistAlbum) }, new List<MenuType>() { MenuType.Item, MenuType.Play }));
                kernel.AddMenuItem(new MenuItem("Queue", "resx://MediaBrowser/MediaBrowser.Resources/Lines", this.queue, new List<Type>() { typeof(Song) }, new List<MenuType>() { MenuType.Item, MenuType.Play }));
            }

            kernel.EntityResolver.Insert(kernel.EntityResolver.Count - 2, new SongResolver());
            kernel.EntityResolver.Insert(kernel.EntityResolver.Count - 2, new ArtistAlbumResolver());
            kernel.EntityResolver.Insert(kernel.EntityResolver.Count - 2, new MusicFolderResolver());
            PlayableItemFactory.Instance.PlayableItems.Add(PlayableMusicFile.CanPlay, typeof(PlayableMusicFile));
            PlayableItemFactory.Instance.PlayableItems.Add(PlayableMultiFileMusic.CanPlay, typeof(PlayableMultiFileMusic));
            kernel.PlaybackControllers.Insert(0, new PlaybackControllerMusic());
            MediaBrowser.Library.ItemFactory.Instance.AddFactory(MusicFolderModel.IsOne, typeof(MusicFolderModel));
        }

        private static void LoadLibraries(Kernel kernel, bool isConfigurator)
        {
            if (Settings.Instance.LoadiTunesLibrary)
            {
                LoadiTunesLibrary(kernel, isConfigurator);
            }

            if (Settings.Instance.LoadNormalLibrary)
            {
                LoadNormalLibrary(kernel);
            }
        }
        public override System.Version RequiredMBVersion
        {
            get
            {
                return Global.PLUGIN_REQUIRED_MB_VERSION;
            }
        }
        public override System.Version TestedMBVersion
        {
            get
            {
                return Global.PLUGIN_TESTED_MB_VERSION;
            }
        }
        private static void LoadNormalLibrary(Kernel kernel)
        {
            if (Settings.ValidateNormalLibrary(true))
            {
                BaseItem music;

                music = kernel.ItemRepository.RetrieveItem(Global.MUSIC_NORMAL_GUID) ?? new MusicPluginFolder();
                music.Id = Global.MUSIC_NORMAL_GUID;
                Logger.ReportInfo("Music normal id - " + music.Id);
                music.Path = Settings.Instance.NormalLibraryPath;
                Logger.ReportInfo("Music normal path - " + music.Path);
                music.Name = Settings.Instance.NormalLibraryVirtualFolderName;
                Logger.ReportInfo("Music normal name - " + music.Name);
                if (!string.IsNullOrEmpty(Settings.Instance.NormalLibraryIcon))
                    music.PrimaryImagePath = Settings.Instance.NormalLibraryIcon;
                kernel.RootFolder.AddVirtualChild(music);
                kernel.ItemRepository.SaveItem(music);
                //add types to supported types
                kernel.AddExternalPlayableItem(typeof(Song));
                kernel.AddExternalPlayableFolder(typeof(ArtistAlbum));
            }
        }

        private static void LoadiTunesLibrary(Kernel kernel, bool isConfigurator)
        {
            if (Settings.ValidateiTunesLibrary(true))
            {
                try
                {
                    BaseItem itunes;
                    string message = "Refresh iTunes Library is set to true, this will force a rebuild of the iTunes Library, continue?";
                    string heading = "Rebuild iTunes Library Cache";

                    if (Settings.Instance.ForceRefreshiTunesLibrary && (isConfigurator || Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.Dialog(message, heading, DialogButtons.Yes | DialogButtons.No, 60, true) == DialogResult.Yes))
                    {

                        itunes = iTunesLibrary.GetDetailsFromXml(kernel.ItemRepository.RetrieveItem(Global.MUSIC_ITUNES_GUID) as iTunesMusicLibrary);
                        Settings.Instance.ForceRefreshiTunesLibrary = false;
                        Settings.SaveSettingsFile();

                    }
                    else
                    {
                        itunes = kernel.ItemRepository.RetrieveItem(Global.MUSIC_ITUNES_GUID) ?? new iTunesLibrary().Library;
                    }
                    if (((iTunesMusicLibrary)itunes).LastUpdate != DateTime.MinValue && (itunes as iTunesMusicLibrary).LastUpdate < new System.IO.FileInfo(Settings.Instance.iTunesLibraryXMLPath).LastWriteTime)
                    {
                        message = "Your iTunes Library might have changed, do you want to rebuild it?";
                        if (isConfigurator || Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.Dialog(message, heading, DialogButtons.Yes | DialogButtons.No, 60, true) == DialogResult.Yes)
                            itunes = iTunesLibrary.GetDetailsFromXml(kernel.ItemRepository.RetrieveItem(Global.MUSIC_ITUNES_GUID) as iTunesMusicLibrary);

                    }

                    itunes.Path = "";
                    itunes.Id = Global.MUSIC_ITUNES_GUID;
                    Logger.ReportInfo("Music iTunes id - " + itunes.Id);
                    itunes.Name = Settings.Instance.iTunesLibraryVirtualFolderName;
                    Logger.ReportInfo("Music iTunes vf name - " + itunes.Name);
                    if (!string.IsNullOrEmpty(Settings.Instance.iTunesLibraryIcon))
                        itunes.PrimaryImagePath = Settings.Instance.iTunesLibraryIcon;

                    kernel.RootFolder.AddVirtualChild(itunes);
                    kernel.ItemRepository.SaveItem(itunes);
                    //add types to supported types
                    kernel.AddExternalPlayableItem(typeof(iTunesSong));
                    kernel.AddExternalPlayableFolder(typeof(iTunesAlbum));

                }
                catch (Exception ex)
                {
                    Logger.ReportException("Cannot load iTunes Music Library", ex);
                }
            }
        }

        #region testing code
        //System.Timers.Timer t = new System.Timers.Timer(10000);

        //void SetupTestingTimer()
        //{
        //    t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
        //    t.Start();
        //}
                
        //void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    if (MediaBrowser.Application.CurrentInstance.CurrentItem.BaseItem is Song)
        //    {
        //        string time = (string)MediaBrowser.Application.CurrentInstance.CurrentItem.DynamicProperties["ProductionYear"];
        //        Logger.ReportInfo("reading production year" + time);
        //    }
        //}
        #endregion
        public override string Name
        {
            get { return Global.PLUGIN_NAME; }
        }

        public override string Description
        {
            get { return Global.PLUGIN_DESCRIPTION; }
        }
        public override System.Version LatestVersion
        {
            get
            {
                return Global.PLUGIN_VERSION;
            }
            set
            {
                //base.LatestVersion = value;
            }
        }

        public override System.Version Version
        {
            get
            {
                return Global.PLUGIN_VERSION;
            }
        }


        public override bool IsConfigurable
        {
            get
            {
                return Global.PLUGIN_IS_CONFIGURABLE;
            }
        }

        public override string RichDescURL
        {
            get
            {
                return Global.PLUGIN_RICHURL;
            }
        }

        public override void Configure()
        {
            Settings.InitSettings(_kernel.ConfigData.InitialFolder);
            if (ConfigureView.BuildUI(Settings.Instance) == System.Windows.Forms.DialogResult.OK)
            {
                Settings.SaveSettingsFile();
            }
        }

        private void queue(Item item)
        {
            Application.CurrentInstance.AddToQueue(item);
        }
    }
}
